<template xlang="wxml">
  <view>
    <u-popup :show="showTree" :round="10">
      <view style="height: 80vh">
        <u-toolbar
          :cancel-color="cancelColor"
          :confirm-color="confirmColor"
          :title="title"
          @cancel="cancel"
          @confirm="confirm"
        />
        <scroll-view class="tki-tree-view-sc" :scroll-y="true">
          <block v-for="(item, index) in treeList" :key="index">
            <view
              class="tki-tree-item"
              :style="[{
                paddingLeft: item.rank*15 + 'px',
                zIndex: item.rank*-1 +50
              }]"
              :class="{
                border: border === true,
                show: item.show,
                last: item.lastRank,
                showchild: item.showChild,
                open: item.open,
              }">
              <view class="tki-tree-label" @tap.stop="treeItemTap(item, index)">
                <image
                  class="tki-tree-icon"
                  :src="item.lastRank ? lastIcon : item.showChild ? currentIcon : defaultIcon"/>
                {{ item.name }}
              </view>
              <view
                v-if="selectParent?true:item.lastRank" class="tki-tree-check"
                @tap.stop="treeItemSelect(item, index)">
                <view
                  v-if="item.checked" class="tki-tree-check-yes" :class="{'radio':!multiple}"
                  :style="{'border-color':confirmColor}">
                  <view class="tki-tree-check-yes-b" :style="{'background-color':confirmColor}"/>
                </view>
                <view
                  v-else class="tki-tree-check-no" :class="{'radio':!multiple}"
                  :style="{'border-color':confirmColor}"/>
              </view>
            </view>
          </block>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  name: 'TreeSelectPopup',
  props: {
    list: {
      type: Array,
      default: function () {
        return []
      }
    },
    idKey: {
      type: String,
      default: 'id'
    },
    rangeKey: {
      type: String,
      default: 'name'
    },
    title: {
      type: String,
      default: '请选择'
    },
    multiple: { // 是否可以多选
      type: Boolean,
      default: false
      // default: true
    },
    selectParent: { // 是否可以选父级
      type: Boolean,
      default: false
    },
    foldAll: { // 折叠时关闭所有已经打开的子集，再次打开时需要一级一级打开
      type: Boolean,
      default: false
    },
    confirmColor: { // 确定按钮颜色
      type: String,
      default: '' // #07bb07
    },
    cancelColor: { // 取消按钮颜色
      type: String,
      default: '' // #757575
    },
    titleColor: { // 标题颜色
      type: String,
      default: '' // #757575
    },
    currentIcon: { // 展开时候的ic
      type: String,
      default: ''
    },
    defaultIcon: { // 折叠时候的ic
      type: String,
      default: ''
    },
    lastIcon: { // 没有子集的ic
      type: String,
      default: ''
    },
    border: { // 是否有分割线
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showTree: false,
      treeList: [],
      selectId: undefined
    }
  },
  computed: {},
  watch: {
    list: {
      deep: true,
      immediate: true,
      handler(val) {
        this.initTree(val)
      }
    },
    multiple: {
      deep: true,
      immediate: true,
      handler() {
        if (this.list.length) {
          this.reTreeList()
        }
      }
    },
    selectParent: {
      deep: true,
      immediate: true,
      handler() {
        if (this.list.length) {
          this.reTreeList()
        }
      }
    }
  },
  mounted() {
    this.initTree()
  },
  methods: {
    show(val) {
      this.showTree = true
      this.selectId = val
      this.defaultSelect(val)
    },
    hide() {
      this.showTree = false
    },
    cancel() {
      this.hide()
      this.$emit('cancel', '')
    },
    confirm() {
      // 处理所选数据
      const rt = []
      let obj = {}
      this.treeList.forEach((v, i) => {
        if (this.treeList[i].checked) {
          obj = {}
          obj.parents = this.treeList[i].parents
          obj = Object.assign(obj, this.treeList[i].source)
          // 移除子元素
          delete obj.children
          rt.push(obj)
        }
      })
      this.hide()
      this.$emit('confirm', rt)
    },
    // 扁平化树结构
    renderTreeList(list = [], rank = 0, parentId = [], parents = []) {
      list.forEach(item => {
        this.treeList.push({
          id: item[this.idKey],
          name: item[this.rangeKey],
          source: item,
          parentId, // 父级id数组
          parents, // 父级id数组
          rank, // 层级
          showChild: false, // 子级是否显示
          open: false, // 是否打开
          show: rank === 0, // 自身是否显示
          hideArr: [],
          orChecked: item.checked ? item.checked : false,
          checked: item.checked ? item.checked : false
        })
        if (Array.isArray(item.children) && item.children.length > 0) {
          // console.log(item)
          var parentid = [...parentId]
          var parentArr = [...parents]
          var childrenid = childrenid
          delete parentArr.children
          parentid.push(item[this.idKey])
          parentArr.push({
            [this.idKey]: item[this.idKey],
            [this.rangeKey]: item[this.rangeKey]
          })
          this.renderTreeList(item.children, rank + 1, parentid, parentArr)
        } else {
          this.treeList[this.treeList.length - 1].lastRank = true
        }
      })
    },
    // 处理默认选择
    defaultSelect(val) {
      if (this.isNull(val)) {
        return
      }
      this.treeList.forEach((v, i) => {
        if (v[this.idKey] === val) {
          v.checked = true
          this.treeList.forEach((v2, i2) => {
            if (v.parentId.toString().indexOf(v2.parentId.toString()) >= 0) {
              // console.log(v2, v.parentId.toString().indexOf(v2.parentId.toString()))
              v2.show = true
              // if(v2.rank>0){
              // 	v2.show=false
              // }
              if (v.parentId.includes(v2.id)) {
                v2.showChild = true
                v2.open = true
              }
            }
          })
        } else {
          v.checked = false
        }
      })
    },
    // 点击
    treeItemTap(item, index) {
      if (item.lastRank === true) {
        // 点击最后一级时触发事件
        this.treeList[index].checked = !this.treeList[index].checked
        this.fixMultiple(index)
        return
      }
      const list = this.treeList
      const id = item.id
      item.showChild = !item.showChild
      item.open = item.showChild ? true : !item.open
      list.forEach((childItem, i) => {
        if (item.showChild === false) {
          // 隐藏所有子级
          if (!childItem.parentId.includes(id)) {
            return
          }
          if (!this.foldAll) {
            if (childItem.lastRank !== true && !childItem.open) {
              childItem.showChild = false
            }
            // 为隐藏的内容添加一个标记
            if (childItem.show) {
              childItem.hideArr[item.rank] = id
            }
          } else {
            if (childItem.lastRank !== true) {
              childItem.showChild = false
            }
          }
          childItem.show = false
        } else {
          // 打开子集
          if (childItem.parentId[childItem.parentId.length - 1] === id) {
            childItem.show = true
          }
          // 打开被隐藏的子集
          if (childItem.parentId.includes(id) && !this.foldAll) {
            // console.log(childItem.hideArr)
            if (childItem.hideArr[item.rank] === id) {
              childItem.show = true
              if (childItem.open && childItem.showChild) {
                childItem.showChild = true
              } else {
                childItem.showChild = false
              }
              childItem.hideArr[item.rank] = null
            }
          }
        }
      })
    },
    treeItemSelect(item, index) {
      this.treeList[index].checked = !this.treeList[index].checked
      this.fixMultiple(index)
    },
    // 处理单选多选
    fixMultiple(index) {
      // console.log(index,'33333');
      if (!this.multiple) {
        // 如果是单选
        this.treeList.forEach((v, i) => {
          if (i !== index) {
            this.treeList[i].checked = false
          } else {
            this.treeList[i].checked = true
          }
        })
      }
    },
    // 重置数据
    reTreeList() {
      this.treeList.forEach((v, i) => {
        this.treeList[i].checked = v.orChecked
      })
    },
    initTree(range = this.list) {
      this.treeList = []
      this.renderTreeList(range)
      this.$nextTick(() => {
        this.defaultSelect(this.selectId)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
